<template>
  <view class="body">
    <view class="title">
      <text class="title_text">血压变化情况</text>
      <view class="date-type-box">
        <text
          @tap="changeDateType('week')"
          :class="dateType === 'week' ? 'date-type action' : 'date-type'"
        >
          周
        </text>
        <text
          @tap="changeDateType('month')"
          :class="dateType === 'month' ? 'date-type action' : 'date-type'"
        >
          月
        </text>
        <text
          @tap="changeDateType('year')"
          :class="dateType === 'year' ? 'date-type action' : 'date-type'"
        >
          年
        </text>
      </view>
    </view>
    <view class="date-box">
      <view class="date-item">
        <view @tap="prevDate" class="date-item date-left">
          <up-icon name="arrow-left" size="18" />
          {{
            dateType == 'week'
              ? parseTime(startDate, '{m}/{d}')
              : parseTime(startDate, '{y}/{m}/{d}')
          }}
        </view>
        <text style="margin: 0 8rpx">-</text>
        <view @tap="nextDate" v-if="nowDate != endDate" class="date-item date-right">
          {{
            dateType == 'week' ? parseTime(endDate, '{m}/{d}') : parseTime(endDate, '{y}/{m}/{d}')
          }}
          <up-icon name="arrow-right" size="18" />
        </view>
        <view v-else class="date-item">
          {{
            dateType == 'week' ? parseTime(endDate, '{m}/{d}') : parseTime(endDate, '{y}/{m}/{d}')
          }}
        </view>
      </view>
      <text class="unit">单位: mmHg</text>
    </view>
    <view>
      <view class="echart">
        <qiun-data-charts
          :canvas2d="true"
          canvasId="sbp"
          type="line"
          :opts="opts"
          :chartData="chartData"
          :ontouch="true"
          tooltipFormat="tooltipFormat"
        />
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import qiunDataCharts from '@/module/common/qiun-data-charts/qiun-data-charts.vue'
import { ref, onMounted, watch } from 'vue'
import { deepCopy, parseTime, throttle, generateDateRange } from '@/utils/tools'
import { bodyInfo } from './echartsInfo.api'

const chart = ref()
const tab = ref('')

const dateType = ref<string>('week')
const startDate = ref<string>('')
const endDate = ref<string>('')
const nowDate = ref<string>('')

const props = defineProps({
  empi: String,
  chartInfo: {
    type: Object,
    default: () => {}
  }
})

const opts = {
  color: ['#5C8EFF', '#FF813C'],
  padding: [20, 30, 10, 0],
  dataLabel: false,
  legend: {
    show: false
  },
  xAxis: {
    disableGrid: true,
    labelCount: 8,
    format: 'hideLabel',
    type: 'week',
    categoriesOrigin: []
  },
  yAxis: {
    gridType: 'dash',
    dashLength: 4,
    gridColor: '#E5E6EB',
    data: [
      {
        axisLine: false,
        min: 0,
        max: 300,
        fontColor: '#999999'
      }
    ]
  },
  extra: {
    line: {
      type: 'straight',
      width: 2,
      activeType: 'hollow'
    },
    markLine: {
      type: 'dash',
      dashLength: 8,
      data: [
        {
          value: 60,
          lineColor: '#FF813C',
          showLabel: true,
          labelAlign: 'right',
          labelPadding: 1,
          labelBgOpacity: 0,
          labelOffsetY: 20,
          labelBgColor: '#fff',
          labelFontSize: 12
        },
        {
          value: 89,
          lineColor: '#FF813C',
          showLabel: true,
          labelAlign: 'right',
          labelPadding: 1,
          labelBgOpacity: 0,
          labelOffsetY: 20,
          labelBgColor: '#fff',
          labelFontSize: 12
        },
        {
          value: 90,
          lineColor: '#5C8EFF',
          showLabel: true,
          labelAlign: 'right',
          labelPadding: 1,
          labelBgOpacity: 0,
          labelOffsetY: -20,
          labelBgColor: '#fff',
          labelFontSize: 12
        },
        {
          value: 139,
          lineColor: '#5C8EFF',
          showLabel: true,
          labelAlign: 'right',
          labelPadding: 1,
          labelBgOpacity: 0,
          labelOffsetY: -20,
          labelBgColor: '#fff',
          labelFontSize: 12
        }
      ]
    },
    tooltip: {
      showBox: true, // 显示 tooltip
      showArrow: true
    }
  }
}

const chartData = ref()
const chart_data = ref()
const categories = ref<any>([])
const categoriesOrigin = ref<any>([]) // 完整年月日

watch(
  () => chart_data.value,
  (n, o) => {
    if (!o || JSON.stringify(n) !== JSON.stringify(o)) {
      chartData.value = deepCopy(n)
    }
  }
)

onMounted(() => {
  categories.value = []
  nowDate.value = parseTime(new Date(), '{y}-{m}-{d}')
  getWeekDateRange(new Date())
})

const getData = async (item: string, name: string) => {
  opts.xAxis.categoriesOrigin = categoriesOrigin.value
  const params = {
    empi: props.empi, // props.empi
    paramKey: 'sbp',
    timeType: dateType.value.toUpperCase(),
    startTime: parseTime(startDate.value, '{y}-{m}-{d} 00:00:00'),
    endTime: parseTime(endDate.value, '{y}-{m}-{d} 23:59:59')
  }

  const paramsdbp = {
    empi: props.empi, // props.empi
    paramKey: 'dbp',
    timeType: dateType.value.toUpperCase(),
    startTime: parseTime(startDate.value, '{y}-{m}-{d} 00:00:00'),
    endTime: parseTime(endDate.value, '{y}-{m}-{d} 23:59:59')
  }

  const series = []
  const data = new Array(categories.value.length).fill(null)
  const data2 = new Array(categories.value.length).fill(null)
  await bodyInfo(params).then((res) => {
    if (res.data && res.data.length > 0) {
      res.data.reverse().map((v) => {
        if (dateType.value === 'year') {
          data[Number(v.dateName) - 1] = v.param_value
        } else {
          const index = parseTime(v.dateName, '{d}')
          const dataIndex = categories.value.findIndex((vo) => Number(vo) == index)
          data[dataIndex] = v.param_value
        }
      })
    }
    series.push({
      connectNulls: true,
      name: '收缩压',
      data: data
    })
  })

  await bodyInfo(paramsdbp).then((res) => {
    if (res.data && res.data.length > 0) {
      res.data.reverse().map((v) => {
        if (dateType.value === 'year') {
          data2[Number(v.dateName) - 1] = v.param_value
        } else {
          const index2 = parseTime(v.dateName, '{d}')
          const dataIndex2 = categories.value.findIndex((vo) => Number(vo) == index2)
          data2[dataIndex2] = v.param_value
          // data2[Number(index2) - Number(parseTime(startDate.value, '{d}'))] = v.param_value
        }
      })
    }
    series.push({
      connectNulls: true,
      name: '舒张压',
      data: data2
    })
  })

  chart_data.value = {
    categories: categories.value,
    series: series
  }
}
// 默认 时间类型为周
const getWeekDateRange = (date: any) => {
  categories.value = []
  categoriesOrigin.value = []
  const week = getYearWeek(date)
  const weekArr = whichWeek(date.getFullYear())
  const wk: any = weekArr[week - 1]

  const startDateObj = new Date(wk.year, wk.month - 1, wk.date)
  let endDateObj = new Date(wk.last.year, wk.last.month - 1, wk.last.date)
  const currentDateObj = new Date()
  if (currentDateObj >= startDateObj && currentDateObj <= endDateObj) {
    endDateObj = currentDateObj
  }
  startDate.value = parseTime(startDateObj, '{y}-{m}-{d}')
  endDate.value = parseTime(endDateObj, '{y}-{m}-{d}')

  // 完整日期
  const fullDates = generateDateRange(startDateObj, endDateObj)
  categoriesOrigin.value = fullDates
  categories.value = fullDates.map(d => Number(d.split('/')[2]))
  
  // const weekEndDateObj = new Date(wk.last.year, wk.last.month - 1, wk.last.date)
  // startDate.value = parseTime(startDateObj, '{y}-{m}-{d}')
  // endDate.value = parseTime(weekEndDateObj, '{y}-{m}-{d}')
  // CateGories.value = generateDateRange(startDateObj, weekEndDateObj)

  getData('sbp', '收缩压')
}

// 获取月类型的时间段
const getMonthDateRange = (date: any) => {
  categories.value = []
  // 通过传入的 date 参数获取目标年份和月份
  const targetYear = date.getFullYear()
  const targetMonth = date.getMonth() + 1 // getMonth() 从 0 开始计数

  // 获取当前日期信息
  const currentYear = new Date().getFullYear()
  const currentMonth = new Date().getMonth() + 1
  const currentDay = new Date().getDate()

  // 格式化月份，确保是两位数
  const formattedMonth = targetMonth < 10 ? `0${targetMonth}` : targetMonth

  let startDateValue
  let endDateValue

  if (targetYear === currentYear && targetMonth === currentMonth) {
    // 如果是当前月份
    startDateValue = `${targetYear}-${formattedMonth}-01`
    endDateValue = `${targetYear}-${formattedMonth}-${
      currentDay < 10 ? `0${currentDay}` : currentDay
    }`
    const len = currentDay - 1
    for (let i = 0; i <= len; i++) {
      const day = 1 + i
      categories.value.push(day)
      categoriesOrigin.value.push(`${targetYear}/${targetMonth}/${day < 10 ? `0${day}` : day}`)
    }
  } else {
    // 如果是过去的月份，获取该月的最后一天
    const lastDay = new Date(targetYear, targetMonth, 0).getDate()
    startDateValue = `${targetYear}-${formattedMonth}-01`
    endDateValue = `${targetYear}-${formattedMonth}-${lastDay}`
    const len = lastDay - 1
    for (let i = 0; i <= len; i++) {
      const day = 1 + i
      categories.value.push(day)
      categoriesOrigin.value.push(`${targetYear}/${formattedMonth}/${day < 10 ? `0${day}` : day}`)
    }
  }
  startDate.value = startDateValue
  endDate.value = endDateValue
  // console.log(categories.value)
  getData('sbp', '收缩压')
}

// 获取年的时间段
const getYearDateRange = (date: any) => {
  categories.value = []
  // 当前年份
  const currentYear = new Date().getFullYear()
  const currentMonth = new Date().getMonth() + 1
  const currentDay = new Date().getDate()

  const targetYear = date.getFullYear()

  startDate.value = `${targetYear}-01-01`
  if (targetYear === currentYear) {
    endDate.value = `${targetYear}-${currentMonth < 10 ? `0${currentMonth}` : currentMonth}-${
      currentDay < 10 ? `0${currentDay}` : currentDay
    }`
    const len = currentMonth - 1
    for (let i = 0; i <= len; i++) {
      const month = 1 + i
      categories.value.push(month)
      categoriesOrigin.value.push(`${targetYear}/${month < 10 ? `0${month}` : month}`)
    }
  } else {
    endDate.value = `${targetYear}-12-31`
    const len = 12 - 1
    for (let i = 0; i <= len; i++) {
      const month = 1 + i
      categories.value.push(month)
      categoriesOrigin.value.push(`${targetYear}/${month < 10 ? `0${month}` : month}`)
    }
  }

  getData('sbp', '收缩压')
}

// 类型切换
const changeDateType = (type: string) => {
  dateType.value = type
  opts.xAxis.type = type
  categoriesOrigin.value = []
  opts.xAxis.categoriesOrigin = []
  const date = new Date()
  switch (type) {
    case 'week':
      getWeekDateRange(date)
      break
    case 'month':
      getMonthDateRange(date)
      break
    case 'year':
      getYearDateRange(date)
      break
    default:
      break
  }
}

const whichWeek = (year: any) => {
  var d = new Date(year, 0, 1)
  while (d.getDay() != 1) {
    d.setDate(d.getDate() + 1)
  }
  const arr = []
  const longnum = d.setDate(d.getDate())
  if (longnum > +new Date(year, 0, 1)) {
    const obj = yearDay(+new Date(year, 0, 1) / 1000)
    obj.last = yearDay(longnum / 1000 - 86400)
    arr.push(obj)
  }
  const oneitem = yearDay(longnum / 1000)
  oneitem.last = yearDay(longnum / 1000 + 86400 * 6)
  arr.push(oneitem)
  let lastStr = 0
  for (var i = 0; i < 51; i++) {
    const long = d.setDate(d.getDate() + 7)
    const obj = yearDay(long / 1000)
    obj.last = yearDay(long / 1000 + 86400 * 6)
    lastStr = long + 86400000 * 6
    arr.push(obj)
  }
  if (lastStr < +new Date(year + 1, 0, 1)) {
    const nextYearFirstDay = new Date(year + 1, 0, 1)
    while (nextYearFirstDay.getDay() !== 1) {
      nextYearFirstDay.setDate(nextYearFirstDay.getDate() + 1)
    }
    const obj = yearDay(lastStr / 1000 + 86400)
    obj.last = yearDay((nextYearFirstDay.getTime() - 86400000) / 1000)
  } else {
    arr[arr.length - 1].last = yearDay(+new Date(year + 1, 0, 1) / 1000 - 86400)
  }
  return arr
}

const yearDay = (long: any) => {
  var time = new Date(long * 1000)
  var year = time.getFullYear()
  var month = time.getMonth() + 1 < 10 ? '0' + (time.getMonth() + 1) : time.getMonth() + 1
  var date = time.getDate() < 10 ? '0' + time.getDate() : time.getDate()
  var yearday = { year, month, date }
  return yearday
}

const getYearWeek = (endDate: any) => {
  //本年的第一天
  const beginDate = new Date(endDate.getFullYear(), 0, 1)
  //星期从0-6,0代表星期天，6代表星期六
  let endWeek = endDate.getDay()
  if (endWeek == 0) {
    endWeek = 7
  }
  let beginWeek = beginDate.getDay()
  if (beginWeek == 0) {
    beginWeek = 7
  }
  //计算两个日期的天数差
  const millisDiff = endDate.getTime() - beginDate.getTime()
  const dayDiff = Math.floor(
    (millisDiff + (beginWeek - endWeek) * (24 * 60 * 60 * 1000)) / 86400000
  )
  return Math.ceil(dayDiff / 7) + 1
}

const prevDate = throttle(() => {
  categoriesOrigin.value = []
  opts.xAxis.categoriesOrigin = []
  if (dateType.value == 'week') {
    const date = new Date(new Date(startDate.value).getTime() - 7 * 24 * 60 * 60 * 1000)
    getWeekDateRange(date)
  } else if (dateType.value == 'month') {
    // 创建一个新的日期对象用于计算上个月的日期
    const lastMonthDate = new Date(startDate.value)
    // 设置上个月
    lastMonthDate.setMonth(lastMonthDate.getMonth() - 1)
    getMonthDateRange(lastMonthDate)
  } else {
    // 创建一个新的日期对象用于计算去年的日期
    const lastYearDate = new Date(startDate.value)
    // 设置去年
    lastYearDate.setFullYear(lastYearDate.getFullYear() - 1)
    getYearDateRange(lastYearDate)
  }
}, 300)
const nextDate = throttle(() => {
  categoriesOrigin.value = []
  opts.xAxis.categoriesOrigin = []
  if (dateType.value == 'week') {
    const date = new Date(new Date(startDate.value).getTime() + 7 * 24 * 60 * 60 * 1000)
    getWeekDateRange(date)
  } else if (dateType.value == 'month') {
    // 创建一个新的日期对象用于计算上个月的日期
    const lastMonthDate = new Date(startDate.value)
    // 设置上个月
    lastMonthDate.setMonth(lastMonthDate.getMonth() + 1)
    getMonthDateRange(lastMonthDate)
  } else {
    // 创建一个新的日期对象用于计算去年的日期
    const lastYearDate = new Date(startDate.value)
    // 设置去年
    lastYearDate.setFullYear(lastYearDate.getFullYear() + 1)
    getYearDateRange(lastYearDate)
  }
}, 300)
defineExpose({
  getData
})
</script>

<style lang="scss" scoped>
.body {
  padding: 32rpx;
  margin-bottom: 32rpx;
  background: #fff;

  .echart {
    width: 100%;
    height: 360rpx !important;
  }

  .title {
    display: flex;
    gap: 16rpx;
    align-items: center;
    justify-content: space-between;
    height: 68rpx;
    padding-bottom: 10rpx;
    border-bottom: 1rpx solid #e5e6eb;

    .img_logo {
      width: 32rpx;
      height: 32rpx;
      transform: translateY(6rpx);
    }

    .title_text {
      font-size: 32rpx;
      font-weight: 600;
      color: #222;
    }
  }

  .unit {
    font-size: 24rpx;
    font-weight: 400;
    color: #666;
  }

  .xtitle {
    display: flex;
    flex-wrap: nowrap;
    justify-content: space-around;
    padding-left: 50rpx;

    .xtext {
      font-size: 24rpx;
      font-weight: 400;
      color: #666;
    }
  }
}

.date-type-box {
  display: flex;
  gap: 12rpx;
  width: 144rpx;
  height: 48rpx;
  background: #f3f7f8;
  // border: 1rpx solid #00d1b6;
  border-radius: 34rpx;
  transform: rotateZ(360deg);
}

.date-type {
  display: inline-block;
  width: 48rpx;
  height: 44rpx;
  font-size: 24rpx;
  font-weight: 400;
  line-height: 44rpx;
  color: #666;
  text-align: center;
}

.date-type.action {
  font-weight: 500;
  color: #fff;
  background-color: #00d1b6;
  border-radius: 40rpx;
}

.date-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 16rpx;
  font-size: 22rpx;
}

.date-item {
  display: flex;
  align-items: center;
  font-size: 26rpx;
}

.date-left {
  padding-left: 24rpx;
  margin-left: -24rpx;
}

.date-right {
  padding-right: 24rpx;
}
</style>
